#include "moduleSelect.h"
#define	_SYSTIMER_GLOBAL_
#include "config.h"

U32 fastTickCountLast;
U32 fastTickReload;
void fastTickFlushInt(void)
{
	U32 fastTickRollBack;
	U32 fastTickCountNow;

	_DI();
	fastTickRollBack = SysTick->CTRL&SysTick_CTRL_COUNTFLAG;
	fastTickCountNow = SysTick->VAL&SysTick_VAL_CURRENT;

	if (fastTickCountNow < fastTickCountLast)
	{
		fastTickCount += fastTickCountLast - fastTickCountNow;
	}
	else if (fastTickCountNow == fastTickCountLast && fastTickRollBack)
	{
		fastTickCount += fastTickReload;
	}
	else
	{
		fastTickCount += fastTickCountLast + (fastTickReload - fastTickCountNow);
	}

	fastTickCountLast = fastTickCountNow;
	_EI();
}

void fastTickInit(void)
{
	fastTickCount = 0;
	fastTickReload = SysTick->LOAD&SysTick_LOAD_RELOAD;
	fastTickCountLast = SysTick->VAL&SysTick_VAL_CURRENT;
}

void SysTickDeInit(void)
{
	SysTick->CTRL = 0;
}

void SysTickInit(void)
{
	tickCount = 0;
	/* Setup SysTick Timer for 1 msec interrupts	*/
	if (SysTick_Config(SystemFrequency / 1000))
	{ 
		/* Capture error */ 
		while (1);
	}

	fastTickInit();
}

uint32 GetTickCount(void)
{
	return tickCount;
}

void DelayTimer(uint32 para)
{
	U32 innerTime = GetTickCount();
	while (GetTickCount() - innerTime <= para)
	{
		UARTTxFreeIdleProc();
		WDR();
	}
}

